package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.CollectionBehaviorDto;
import com.heima.behavior.pojos.ApCollectionBehavior;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.CollectionBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author DiXiaoNie
 * @since 2023/1/3 20:25
 */
@Service
public class CollectionBehaviorServiceImpl implements CollectionBehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 收藏
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/03
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {


        //1.参数校验
        if (dto == null || dto.getEntryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取用户登录ID
        ApUser apUser = ApThreadLocalUtil.getApUserThreadLocal();
        //判断是是否是游客登录
        if (apUser == null || apUser.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查看当前用户是否收藏过
        /**
         * 操作类型
         * 0收藏
         * 1取消收藏
         */
        String collectionKey = "USER_COLLECTION_" + dto.getEntryId();
        Boolean collectionFlag = this.redisTemplate.opsForHash().hasKey(collectionKey, apUser.getId().toString());
        // 3.1 如果收藏过，而此时的动作还是收藏行为， operation = 0 则取消返回
        if (collectionFlag && dto.getOperation() == 0) {
            return ResponseResult.errorResult(5001, "您已收藏过此文章");
        }
        // 3.2 如果没有收藏过，而此时的动作还是取消收藏行为， operation = 1 则取消返回
        if (!collectionFlag && dto.getOperation() == 1) {
            return ResponseResult.errorResult(5001, "您还没有收藏过此文章，请收藏后在做出此操作");
        }
        //UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        //updateArticleMess.setArticleId(dto.getEntryId());
        //updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        // 3.3 如果收藏过，而此时的动作是取消收藏行为，operation = 1 则删除redis和mongo
        if (collectionFlag && dto.getOperation() == 1) {
            //删除redis
            this.redisTemplate.opsForHash().delete(collectionKey, apUser.getId().toString());
            //删除mongo
            this.mongoTemplate.remove(Query.query(
                    Criteria.where("userId").is(apUser.getId()).and("articleId").is(dto.getEntryId())
            ), ApFollowBehavior.class);

            //updateArticleMess.setAdd(-1);
            //kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));
            return ResponseResult.okResult("取消收藏成功");

        }
        // 3.4 如果没有收藏过，而此时的动作是收藏行为，operation = 0 则新增redis和mongo
        if (!collectionFlag && dto.getOperation() == 0) {
            //添加redis
            this.redisTemplate.opsForHash().put(collectionKey, apUser.getId().toString(), "1");
            //添加mongo
            ApCollectionBehavior apCollectionBehavior = new ApCollectionBehavior();
            BeanUtils.copyProperties(dto, apCollectionBehavior);
            apCollectionBehavior.setUserId(apUser.getId().longValue());
            apCollectionBehavior.setCollectionTime(new Date());

            this.mongoTemplate.insert(apCollectionBehavior);
        }

        //updateArticleMess.setAdd(1);
        //kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult("收藏成功");
    }

}
